import { i18nRender } from '@/locales';
import './index.less';

export default {
    name: 'STable',
    props: {
        rowKey: {
            type: [String, Function],
            default: 'uuid'
        },
        dataSource: {
            type: Function,
            require: true
        },
        columns: {
            type: Array,
            require: true
        },
        pagination: {
            type: Object,
            default: () => {
                return {};
            }
        }
    },
    data() {
        return {
            tableData: [],
            loading: false,
            localPagination: {},
            filters: {},
            sorter: {}
        };
    },
    computed: {
        totalPage() {
            return Math.ceil(this.localPagination.total / this.localPagination.pageSize);
        }
    },
    created() {
        const pagination = { ...this.getDefaultPagination(), ...this.pagination };
        this.$set(this, 'localPagination', pagination);
        this.loadData();
    },
    methods: {
        /**
         * 加载数据方法
         * @param {Object} pagination 分页选项器
         * @param {Object} filters 过滤条件
         * @param {Object} sorter 排序条件
         */
        loadData(pagination = this.localPagination, filters = this.filters, sorter = this.sorter) {
            this.loading = true;
            this.$emit('loading', true);
            this.filters = filters;
            this.sorter = sorter;
            // 分页
            const { current, pageSize } = pagination;
            const paginationParams = {
                page: current > 0 ? current - 1 : undefined,
                size: pageSize
            };
            // 排序
            const orderMap = {
                ascend: 'asc',
                descend: 'desc'
            };
            const { field, order } = sorter;
            const sortParams = {
                sort: orderMap[order] ? `${field},${orderMap[order]}` : undefined
            };
            // 检索参数
            const params = {
                ...paginationParams,
                ...sortParams,
                ...filters
            };
            this.dataSource(params).then(res => {
                if (`${res.code}` === '0') {
                    this.tableData = res.data.content || res.data.list;
                    console.log(
                        '%ctable.data',
                        'color: #fff; background: #2468f2; padding: 0 4px; border-radius: 2px',
                        this.tableData
                    );
                    this.localPagination.current = current;
                    this.localPagination.pageSize = pageSize;
                    this.localPagination.total = res.data.totalElements;
                    this.loading = false;
                    this.$emit('loading', false);
                } else {
                    this.loading = false;
                    this.$message.error(res.message);
                }
            }).finally(() => {
                this.loading = false;
            });
        },
        /**
         * 获取默认分页配置
         * @returns {Object} 默认分页配置
         */
        getDefaultPagination() {
            return {
                total: 0,
                current: 0,
                pageSize: 10,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ['10', '25', '50', '100'],
                showTotal: (total, range) => {
                    const pageSize = this.localPagination.pageSize;
                    const totalPage = this.totalPage;
                    const currentPage = Math.ceil(range[0] / pageSize);
                    const info = `${i18nRender('common.pageAll')} ${total}
                        ${i18nRender('common.pageRecord')} ${i18nRender('common.pagePrefix')}
                        ${currentPage} / ${totalPage} ${i18nRender('common.page')}`;
                    return info;
                }
            };
        },
        /**
         * 表格刷新方法
         * @param {Boolean}} force 是否强制刷新到第一页
         * @param {Number} timeout 延迟刷新时间
         */
        refresh(force = false, timeout = 0) {
            setTimeout(() => {
                if (force) this.localPagination.current = 1;
                this.loadData();
            }, timeout);
        }
    },
    render() {
        const props = {
            ...this.$attrs,
            rowKey: this.rowKey,
            columns: this.columns,
            dataSource: this.tableData,
            loading: this.loading,
            pagination: this.localPagination
        };
        const on = {
            ...this.$listeners,
            change: this.loadData
        };
        return (
            <a-table class="custom-table" {...{ props, scopedSlots: { ...this.$scopedSlots } }} on={on}>
                {Object.keys(this.$slots).map(name => (
                    <template slot={name}>{this.$slots[name]}</template>
                ))}
            </a-table>
        );
    }
};
